package com.puyuba.puyuba.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hjq.toast.ToastUtils;
import com.puyuba.puyuba.R;
import com.puyuba.puyuba.bean.DownCardBean;
import com.puyuba.puyuba.bean.SimpleMap;
import com.puyuba.puyuba.bean.TextselectBean;
import com.puyuba.puyuba.network.UserApi;
import com.puyuba.puyuba.view.adapter.ChooseAdatper;
import com.puyuba.puyuba.view.adapter.ChooseNeedAdatper;
import com.pyb.java.basemodule.BaseActivity;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.cache.bean.UserInfoBean;
import com.pyb.java.commonutil.ToastHelper;
import com.pyb.java.commonutil.eventbus.EventBusKeys;
import com.pyb.java.commonutil.eventbus.EventBusUtils;
import com.pyb.java.commonutil.utils.RegularUtils;
import com.pyb.java.commonutil.utils.StringUtil;
import com.pyb.java.network.RequestBodyUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;
import com.pyb.java.network.scheduler.RxSchedulers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

/**
 * 添加用户页面
 */
public class AddStudentActivity extends BaseActivity {
    
    private ImageView ivBack;
    private EditText etName;
    private TextView tvEdu;
    private EditText etPhone;
    private EditText etWeixin;
    private EditText etQq;
    private TextView tvIndustry;
    private TextView tvLevel1;
    private TextView tvLevel2;
    private TextView tvLevel3;
    private TextView tvLevel4;
    private TextView tvEduRequi;
    private RecyclerView rclProfession;
    private EditText etOther;
    private TextView intentionLevel1;
    private TextView intentionLevel2;
    private TextView tvAdd;
    private List<String> customlist = Arrays.asList("本科","专科");
    private List<String> customlist2 = Arrays.asList("IT","学生","教育行业","公务员/事业单位","房地产","自由职业","其他");
    String list2 = "[{\"name\":\"教师资格\"},{\"name\":\"建筑工程\"},{\"name\":\"医护药师\"},{\"name\":\"金融考试\"},{\"name\":\"人力资源\"},{\"name\":\"英语考级\"}," +
            "{\"name\":\"营养健康\"},{\"name\":\"经济财会\"},{\"name\":\"其他\"},]";
    private List<String> customlist3 = Arrays.asList("小学","初中","高中","中专","大专","本科","研究生");
    private List<TextselectBean> professionlist;

    private List<TextView> textViewList = new ArrayList<>();
    private String profession;
    private int formposition;
    private ChooseNeedAdatper needAdatper;
    private String level = "";
    private int assignedway = 0;
    private String phone;
    private String name;
    private int size;
    private int category = 0;
    private UserInfoBean userInfoBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_student;
    }

    public static void startActivity(Context context,int id) {
        Intent intent = new Intent(context, AddStudentActivity.class);
        intent.putExtra("id",id);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        etName = (EditText) findViewById(R.id.et_name);
        tvEdu = (TextView) findViewById(R.id.et_edu);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etWeixin = (EditText) findViewById(R.id.et_weixin);
        etQq = (EditText) findViewById(R.id.et_qq);
        tvIndustry = (TextView) findViewById(R.id.tv_industry);
        tvLevel1 = (TextView) findViewById(R.id.tv_level1);
        tvLevel2 = (TextView) findViewById(R.id.tv_level2);
        tvLevel3 = (TextView) findViewById(R.id.tv_level3);
        tvLevel4 = (TextView) findViewById(R.id.tv_level4);
        tvEduRequi = (TextView) findViewById(R.id.tv_edu_requi);
        rclProfession = (RecyclerView) findViewById(R.id.rcl_profession);
        etOther = (EditText) findViewById(R.id.et_other);
        intentionLevel1 = (TextView) findViewById(R.id.intention_level1);
        intentionLevel2 = (TextView) findViewById(R.id.intention_level2);
        tvAdd = (TextView) findViewById(R.id.tv_add);

        int id = getIntent().getIntExtra("id", 0);

        initData();
        initListener();
    }

    private void initData() {
        professionlist = JSONObject.parseArray(list2, TextselectBean.class);
        needAdatper = new ChooseNeedAdatper(R.layout.item_recycleview_choose_need);
        GridLayoutManager manager = new GridLayoutManager(AddStudentActivity.this,3);
        manager.setOrientation(GridLayoutManager.VERTICAL);

        rclProfession.setLayoutManager(manager);
        rclProfession.setAdapter(needAdatper);
        needAdatper.setNewData(professionlist);

        needAdatper.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                profession = professionlist.get(position).getName();
                category = 820201;
                formposition = position;
                for (int a = 0; a < professionlist.size(); a++){
                    if (a == formposition){
                        professionlist.get(a).setSelect(true);
                    }else {
                        professionlist.get(a).setSelect(false);
                    }
                }
                needAdatper.notifyDataSetChanged();
                tvEduRequi.setText("");
            }
        });

        Collections.addAll(textViewList,tvLevel1,tvLevel2,tvLevel3,tvLevel4);
        userInfoBean = CacheUserInfo.getInstance().getsUserInfo();
    }

    private void initListener() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvEduRequi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showEduPickerView();
            }
        });
        tvIndustry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showIndustryPickerView();
            }
        });
        tvEdu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCurEduPickerView();
            }
        });
        tvLevel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changestatus(0);
                level = "A";
            }
        });
        tvLevel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changestatus(1);
                level = "B";
            }
        });
        tvLevel3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changestatus(2);
                level = "C";
            }
        });
        tvLevel4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changestatus(3);
                level = "D";
            }
        });
        intentionLevel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentionLevel1.setTextColor(ContextCompat.getColor(AddStudentActivity.this,R.color.white));
                intentionLevel1.setBackgroundResource(R.drawable.bg_004d80_dp9);
                intentionLevel2.setTextColor(ContextCompat.getColor(AddStudentActivity.this,R.color.color_9B));
                intentionLevel2.setBackgroundResource(R.drawable.shape_input_bg);
                //指派对象 1 自己 2 贡献
                assignedway = 1;
            }
        });
        intentionLevel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentionLevel2.setTextColor(ContextCompat.getColor(AddStudentActivity.this,R.color.white));
                intentionLevel2.setBackgroundResource(R.drawable.bg_004d80_dp9);
                intentionLevel1.setTextColor(ContextCompat.getColor(AddStudentActivity.this,R.color.color_9B));
                intentionLevel1.setBackgroundResource(R.drawable.shape_input_bg);
                assignedway = 2;
            }
        });
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkCommitData();
            }
        });
    }

    private void checkCommitData() {
        name = etName.getText().toString().trim();
        if(StringUtil.isEmpty(name)){
            ToastHelper.show("请输入姓名");
            return;
        }
        phone = etPhone.getText().toString().replaceAll(" ","").trim();
        if(StringUtil.isEmpty(phone)){
            ToastHelper.show("请先输入手机号哦");
            return;
        }
        if(!RegularUtils.isMobile(phone)) {
            ToastHelper.show("手机号格式错误");
            return;
        }
        if (level.equals("")){
            ToastHelper.show("请选择意向等级");
            return;
        }
        if (category == 0){
            ToastHelper.show("请选择需求");
            return;
        }
        if (assignedway == 0){
            ToastHelper.show("请选择指派对象");
            return;
        }

        addUser();
    }

    private void addUser() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid",userInfoBean.getUser().getCrm_user_id());
        map.put("name", name);
        map.put("level", level);
        map.put("mobile", phone);
        map.put("assigned_way", assignedway);
        map.put("category", category);
        map.put("edulevelid", SimpleMap.getInstance().getValue(profession));
        map.put("industry", SimpleMap.getInstance().getIndustryValue(tvIndustry.getText().toString()));
        map.put("size", size);
        map.put("weixin", etWeixin.getText().toString().trim());
        map.put("qq", etQq.getText().toString().trim());
        map.put("contactlog", etOther.getText().toString().trim());
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);
        showLoadingDialog();
        RetrofitManger.getInstance().createService(UserApi.class)
                .add(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<Object>>applySchedulers())
                .subscribe(new ResponseObserve<Object>(){

                    @Override
                    public void onSuccess(ResponseEntity<Object> responseEntity) {
                        closeLoadingDialog();
                        ToastHelper.show("添加成功");
                        finish();
                    }
                    @Override
                    public void onFail(String errorMsg) {
                        closeLoadingDialog();
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@NonNull Disposable disposable) {
                        addDisposable(disposable);
                    }
                });
    }

    private void changestatus(int posi) {
        for (int i = 0; i < textViewList.size(); i++) {
            if (posi == i){
                textViewList.get(i).setTextColor(ContextCompat.getColor(AddStudentActivity.this,R.color.white));
                textViewList.get(i).setBackgroundResource(R.drawable.bg_004d80_dp9);
            }else {
                textViewList.get(i).setTextColor(ContextCompat.getColor(AddStudentActivity.this,R.color.color_9B));
                textViewList.get(i).setBackgroundResource(R.drawable.shape_input_bg);
            }
        }
    }

    private void showEduPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(AddStudentActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
//               返回的分别是三个级别的选中位置
                tvEduRequi.setText(customlist.get(options1));
                for (int a = 0; a < professionlist.size(); a++){
                    professionlist.get(a).setSelect(false);
                }
                needAdatper.notifyDataSetChanged();
                profession = customlist.get(options1);
                category = 820204;
            }
        })
                .setTitleText("")
                .setSelectOptions(0)//设置选择第一个
                .setOutSideCancelable(false)//点击背的地方不消失
                .build();
        pvOptions.setPicker(customlist);
        pvOptions.show();

    }
    private void showIndustryPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(AddStudentActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                tvIndustry.setText(customlist2.get(options1));
            }
        })
                .setTitleText("")
                .setSelectOptions(0)//设置选择第一个
                .setOutSideCancelable(false)//点击背的地方不消失
                .build();
        pvOptions.setPicker(customlist2);
        pvOptions.show();

    }

    private void showCurEduPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(AddStudentActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
//               返回的分别是三个级别的选中位置
                tvEdu.setText(customlist3.get(options1));
                size = options1+1;
            }
        })
                .setTitleText("")
                .setSelectOptions(0)//设置选择第一个
                .setOutSideCancelable(false)//点击背的地方不消失
                .build();
        pvOptions.setPicker(customlist3);
        pvOptions.show();
    }


}
